import { likePost } from '@/api/home'
import { ref } from 'vue'
import { showImagePreview, showSuccessToast, showToast } from 'vant'
import type { likeType } from '@/types/home'
import { patientOrderCancel, patientOrder } from '@/api/consult'
import type { patientConsultOrderItem } from '@/types/consult'
import { OrderType } from '@/enums'
import { patientConsultPrescription } from '@/api/room'
import { codeGet } from '@/api/user'
import type { codeGetType } from '@/types/user'

export const useLike = (type: likeType = 'doc') => {
  const loading = ref(false)
  //  ts在参数在传递时是有一定兼容性的， fn(xx:{a:string}){}      const b={a:'',a2:'',a3:''...}   fn(b) 这样不报错
  const likeEvent = async (i: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    await likePost({
      id: i.id,
      type: type
    })
    loading.value = false
    i.likeFlag = (1 - i.likeFlag) as 0 | 1
    showSuccessToast(i.likeFlag === 1 ? '关注成功' : '取消关注成功')
  }
  return { loading, likeEvent }
}

// 订单取消操作
export const useOrderCancel = () => {
  const loading = ref(false)
  const cancelEvent = async (item: patientConsultOrderItem) => {
    loading.value = true
    try {
      await patientOrderCancel(item.id)
      showSuccessToast('取消成功')
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
    } finally {
      loading.value = false
    }
  }
  return { loading, cancelEvent }
}

// 删除订单操作
export const useOrderDel = (cb: (xx: string) => void) => {
  const delLoading = ref(false)
  const delEvent = async (id: string) => {
    delLoading.value = true
    try {
      await patientOrder(id)
      showSuccessToast('删除成功')
      cb(id)
    } finally {
      delLoading.value = false
    }
  }
  return { delLoading, delEvent }
}

// 查看处方
export const useLook = () => {
  const lookEvent = async (id: string) => {
    const res = await patientConsultPrescription(id)
    showImagePreview([res.data.url])
    console.log('处方信息', res)
  }
  return { lookEvent }
}

// 获取验证码+倒计时功能
const timeTotal = ref(0)
let timeId = -1
export const useMobileCode = (mobile: { value: string }, type: codeGetType) => {
  const cb = async () => {
    const res = await codeGet({
      mobile: mobile.value,
      type: type
    })
    showToast(res.data.code)
    //   到计时
    timeTotal.value = 60
    window.clearInterval(timeId)
    timeId = window.setInterval(() => {
      timeTotal.value--
      if (timeTotal.value <= 0) {
        window.clearInterval(timeId)
        timeTotal.value = 0
      }
    }, 1000)
  }

  return { timeTotal, cb }
}
